package org.brownflat.lighthouse.ci.hudson;

import org.apache.log4j.Logger;
import org.brownflat.lighthouse.ci.ConnectionException;
import org.brownflat.lighthouse.ci.HTTPServer;
import org.brownflat.lighthouse.ci.Monitorable;

public class HudsonServer extends HTTPServer implements Monitorable {
    private static final Logger LOG = Logger.getLogger(HudsonServer.class);
    private String[] views = {""};
    private BrokenBuildDecisionMaker decisionMaker;

    public HudsonServer(String host, int port) {
		super(host, port);		
	}

    public HudsonServer(String host, int port, String path) {
		super(host, port, path);
	}

    public void setBrokenBuildDecisionMaker(BrokenBuildDecisionMaker decisionMaker){
        this.decisionMaker = decisionMaker;
    }

    public void setViews(String[] views) {
        this.views = views;
    }

	@Override
	public boolean hasAnyBrokenBuilds() {
        boolean broken = false;

        for(String view : views) {
            HudsonLatestBuildsRequest request = new HudsonLatestBuildsRequest(view);
            String response = null;
            try {
                response = execute(request);
            } catch (ConnectionException e) {
                LOG.error("Couldn't communicate with Hudson... indicating the build is broken...", e);
                return true;
            }

            if(decisionMaker != null) {
                broken = decisionMaker.broken(response);
                if(LOG.isDebugEnabled()) {
                    LOG.debug(String.format("View [%s] query content [%s], broken [%s]", view, response, broken));
                }
            }

            if(broken) {
                break;
            }
        }
        return broken;
    }

    @Override
    public String getName() {
        return "Hudson";
    }
}
